package com.tttshaoqi.server.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tttshaoqi.common.result.PageResult;
import com.tttshaoqi.common.result.Result;
import com.tttshaoqi.common.constant.RedisConstants;
import com.tttshaoqi.common.utils.EmpHolder;
import com.tttshaoqi.pojo.dto.EmployeeDTO;
import com.tttshaoqi.pojo.dto.LoginDTO;
import com.tttshaoqi.pojo.dto.PassWordDTO;
import com.tttshaoqi.pojo.entity.Employee;
import com.tttshaoqi.pojo.vo.EmployeeLoginVO;
import com.tttshaoqi.server.mapper.EmployeeMapper;
import com.tttshaoqi.server.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 登录账户，并返回token
     * @param loginDTO
     * @return
     */
    public Result login(LoginDTO loginDTO) {
        // 数据库是否存在该用户
        Employee employee = employeeMapper.getByUAP(loginDTO);
        if (employee == null) {
            return Result.error("账号或密码错误");
        }
        if(employee.getStatus() == 0){
            return Result.error("员工账号已禁用");
        }
        EmployeeDTO employeeDTO = new EmployeeDTO();
        BeanUtils.copyProperties(employee,employeeDTO);
        // 将用户信息存入redis
        String token = UUID.randomUUID().toString();
        Map<String,Object> mp = new HashMap<>();
        mp.put("id",""+employeeDTO.getId());
        mp.put("username",employeeDTO.getUserName());
        mp.put("name",employeeDTO.getName());
        redisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,mp);
        // 存储登录信息
        EmpHolder.saveEmp(employeeDTO);
        // 7.4.设置token有效期
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,
                RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        EmployeeLoginVO employeeLoginVO = new EmployeeLoginVO();
        employeeLoginVO.setId(employee.getId());
        employeeLoginVO.setUserName(employee.getUsername());
        employeeLoginVO.setName(employee.getName());
        employeeLoginVO.setToken(token);
        return Result.success(employeeLoginVO);
    }

    @Override
    public PageResult page(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page,pageSize);
        List<Employee> employeeList = employeeMapper.list(name);
        Page<Employee> p = (Page<Employee>) employeeList;
        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 启用或禁用员工
     * @param status
     * @param id
     */
    public void status(Integer status, Long id) {
        Employee employee = Employee.builder()
                .updateTime(LocalDateTime.now())
                .status(status)
                .id(id)
                .build();
        employeeMapper.updateById(employee);
    }

    /**
     * 添加员工信息
     * @param employee
     * @return
     */
    public Result add(Employee employee) {
        // 查询数据库该账号是否存在
        Employee mum = employeeMapper.getByUsername(employee.getUsername());
        if(mum != null){
            // 若已经存在，返回错误信息
            log.info("添加失败，该账号已存在！");
            return Result.error("添加失败，该账号已存在！");
        }
        // 若不存在，则向数据库中添加数据
        employee.setPassword("123456");
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setStatus(1);
        employeeMapper.add(employee);
        return Result.success();
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    public Result getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        if(employee == null){
            return Result.error("该员工不存在");
        }
        return Result.success(employee);
    }

    /**
     * 修改员工信息
     * @param employee
     */
    public void update(Employee employee) {
        employeeMapper.updateById(employee);
    }

    /**
     * 修改密码
     * @param passWordDTO
     * @return
     */
    public Result editPassword(PassWordDTO passWordDTO) {
        Employee employee = employeeMapper.getById(passWordDTO.getId());
        if(employee == null){
            return Result.error("不存在该用户！");
        }
        if(!passWordDTO.getOldPassWord().equals(employee.getPassword())){
            return Result.error("旧密码错误，修改失败！");
        }
        employee.setUpdateTime(LocalDateTime.now());
        employee.setPassword(passWordDTO.getNewPassWord());
        employeeMapper.updateById(employee);
        return Result.success();
    }
}
